package com.abc.cloud.common.filter;

import cn.hutool.json.JSONUtil;
import com.abc.cloud.common.exception.MyException;
import com.abc.cloud.common.utils.JwtUtil;
import com.abc.cloud.common.utils.UserHolder;
import com.abc.cloud.entity.UserEntity;
import com.abc.cloud.service.MenuService;
import com.abc.cloud.service.PermsService;
import com.abc.cloud.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    private final UserService userService;
    private final PermsService permsService;

    public TokenInterceptor(UserService userService,  PermsService permsService) {
        this.userService = userService;
        this.permsService = permsService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        String path = request.getRequestURI();
        log.info("=============================开始=============================");
        log.info("请求token：{}", token);
        log.info("请求路由：{}", path);
        if(StringUtils.isEmpty(token)){
            throw new MyException("请先登录");
//            return false;
        }

        // 检验token的合法性
        String username = JwtUtil.getUsername(token);
        Long userId = JwtUtil.getUserId(token);
        if (StringUtils.isEmpty(username)) {
            throw new MyException("身份过期");
        }
        log.info("身份验证成功");

        // 查询用户权限
        UserEntity userEntity = userService.getById(userId);
        UserHolder.saveUser(userEntity);
        log.info("用户信息：{}", userEntity);

        List<String> userPerms = permsService.queryUserPermsList(userId);
        UserHolder.saveAuthorities(userPerms);
        log.info("用户权限信息：{}", userPerms);

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

}
